from fastapi import  Request, APIRouter
import httpx

router = APIRouter()

# 微信应用 ID 和应用密钥
APP_ID = 'wx688ee8c10c414070'
APP_SECRET = '8f00dc4db29c698079e5960e11e5194d'

# 回调地址
REDIRECT_URI = 'http://127.0.0.1:8000/api/user/register'

@router.get("/wechat_callback")
async def wechat_callback(request: Request):
    code = request.query_params.get("code")
    if code is None:
        return {"message": "授权码获取失败"}
    async with httpx.AsyncClient() as client:
        try:
            access_token_response = await client.get(f'https://api.weixin.qq.com/sns/oauth2/access_token?appid={APP_ID}&secret={APP_SECRET}&code={code}&grant_type=authorization_code')
            access_token_info = access_token_response.json()
            if 'access_token' not in access_token_info:
                return {"message": "获取 access_token 失败"}
            user_info_response = await client.get(f'https://api.weixin.qq.com/sns/userinfo?access_token={access_token_info["access_token"]}&openid={access_token_info["openid"]}')
            user_info = user_info_response.json()
            # 在这里可以处理用户信息并进行登录逻辑
            return {"message": "登录成功", "user_info": user_info}
        except Exception as e:
            return {"message": f"出现错误：{str(e)}"}
